package com.df.springmvc.workflow.api.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Repository;
import com.common.bean.SQLInsertBean;
import com.common.bean.SQLResultBean;
import com.common.util.SN_GUID;
import com.df.springmvc.workflow.ActicityDao;
import com.google.gson.Gson;

/**
 * 本类只做数据库操作处理
 * @author Turner
 */
@Repository
public class APIDao extends ActicityDao{
	public Object doNew(String proc_def_key,String form_guid,String title,HashMap<String,Object> paramMap) throws Exception{
		// TODO Auto-generated method stub
		String sql="select wf_proc_inst_id from S_WF_ProcInst_Info where wf_proc_form_guid=?";
		// 查询是否关联了流程.
		SQLResultBean resultBean=querySqlToSQLResultBean(sql,new Object[]{form_guid});
		if(resultBean.getMapList().size() > 0){
			return resultBean.getMapList().get(0).get("wf_proc_inst_id");
		}else{
			Map<String,Object> variables=new HashMap<String,Object>(paramMap);
			ProcessInstance processInstance=runtimeService.startProcessInstanceByKey(proc_def_key,variables);
			org.apache.log4j.Logger.getLogger(getClass()).info("创建新流程实例" + processInstance.getId());
			SQLInsertBean bean=new SQLInsertBean("S_WF_ProcInst_Info");
			bean.putColumn("guid",SN_GUID.getUUID());
			bean.putColumn("status","1");
			bean.putColumn("createby","apiuser");
			bean.putColumn("createtime",new Date());
			bean.putColumn("updateby","apiuser");
			bean.putColumn("updatetime",new Date());
			bean.putColumn("wf_proc_form_guid",form_guid);
			bean.putColumn("title",title);
			bean.putColumn("description","");
			bean.putColumn("wf_proc_inst_id",processInstance.getId());
			excuteSqlBean(bean);// 关联activiti与系统中唯一ID
			addParam(processInstance.getId(),"",paramMap);
			return processInstance.getId();
		}
	}
	/**
	 * 进行签收
	 * @param taskId
	 * @param userId
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public Object doClaim(String taskId,String userId,HashMap<String,Object> paramMap) throws Exception{
		// TODO Auto-generated method stub
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		// task.setDescription("签收任务");
		if("".equals(userId)){
			throw new RuntimeException("用户不能为空");
		}
		taskService.saveTask(task);
		taskService.claim(taskId,userId);
		return "签收成功";
	}
	public Object doComplete(String taskId,String userId,HashMap<String,Object> paramMap) throws Exception{
		// TODO Auto-generated method stub
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		if(task == null){
			throw new RuntimeException("当前任务编号[" + taskId + "]不存在");
		}
		Map<String,Object> variables=new HashMap<String,Object>(paramMap);
		String title="" + paramMap.get("title");
		task.setDescription("null".equals(title)?"":title);
		org.apache.log4j.Logger.getLogger(getClass()).debug("doComplete:" + paramMap);
		taskService.saveTask(task);
		taskService.complete(taskId,variables);
		addParam(task.getProcessInstanceId(),task.getId(),paramMap);
		return "ok";
	}
	public Object doReAssignee(String taskId,String userId,HashMap<String,Object> paramMap) throws Exception{
		// TODO Auto-generated method stub
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		task.setDescription("转派");
		taskService.setAssignee(task.getId(),userId);
		addParam(task.getProcessInstanceId(),task.getId(),paramMap);
		return "ok";
	}
	public Object doChain(String taskId,String assignee,HashMap<String,Object> paramMap) throws Exception{
		// TODO Auto-generated method stub
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		task.setDescription("加签");
		task.setAssignee(assignee);
		taskService.saveTask(task);
		addParam(task.getProcessInstanceId(),task.getId(),paramMap);
		return "ok";
	}
	public Object queryTaskIdByGuid(String form_guid) throws Exception{
		// TODO Auto-generated method stub
		String sql="select wf_proc_inst_id from S_WF_ProcInst_Info where wf_proc_form_guid=?";
		SQLResultBean resultBean=querySqlToSQLResultBean(sql,new Object[]{form_guid});
		// 查询数据
		ArrayList<Object> list=resultBean.getList(Object.class);
		String processInstanceId="";
		for(Object object:list){
			processInstanceId="" + object;
		}
		if("".equals(processInstanceId)){
			throw new RuntimeException("未找到[" + form_guid + "]关联的流程实例号");
		}
		List<HistoricTaskInstance> taskList=historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
		//
		ArrayList<HashMap<String,Object>> taskIdTmpList=new ArrayList<HashMap<String,Object>>();
		for(HistoricTaskInstance task:taskList){
			HashMap<String,Object> t=new HashMap<String,Object>();
			t.put("id",task.getId());
			t.put("name",task.getName());
			t.put("owner",task.getOwner());
			t.put("processInstanceId",task.getProcessInstanceId());
			t.put("processDefinitionId",task.getProcessDefinitionId());
			t.put("assignee",task.getAssignee());
			t.put("taskLocalVariables",task.getTaskLocalVariables());
			t.put("processVariables",task.getProcessVariables());
			t.put("claimTime",task.getClaimTime());
			t.put("startTime",task.getStartTime());
			t.put("endTime",task.getEndTime());
			// List<HistoricActivityInstance> list2=historyService.create;
			// org.apache.log4j.Logger.getLogger(getClass()).info("========" + list2);
			// for(HistoricActivityInstance variableInstance:list2){
			// System.out.println("--------" + variableInstance);
			// }
			// org.apache.log4j.Logger.getLogger(getClass()).info("========" + list2);
			t.put("description",task.getDescription());
			t.put("dueDate",task.getDueDate());
			t.put("param",getParam(task.getProcessInstanceId(),task.getId()));
			taskIdTmpList.add(t);
		}
		return taskIdTmpList;
	}
	/**
	 * @param form_taskId
	 * @return
	 * @throws Exception
	 */
	public Object queryTaskByTaskId(String form_taskId) throws Exception{
		// TODO Auto-generated method stub
		List<Task> taskList=taskService.createTaskQuery().taskId(form_taskId).list();
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(Task task:taskList){
			HashMap<String,Object> t=new HashMap<String,Object>();
			// Date claimTime=historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).task().getClaimTime();
			t.put("taskId",task.getId());
			t.put("name",task.getName());
			t.put("assignee",task.getAssignee());
			t.put("canClaim",task.getAssignee() == null);
			t.put("canNext",task.getAssignee() != null);
			t.put("parentTaskId()",task.getParentTaskId());
			t.put("owner",task.getOwner());
			t.put("processInstanceId",task.getProcessInstanceId());
			t.put("createtime",df.format(task.getCreateTime()));
			t.put("description",task.getDescription());
			t.put("taskDefId",task.getTaskDefinitionKey());
			t.put("processDefinitionId",task.getProcessDefinitionId());
			t.put("param",getParam(task.getProcessInstanceId(),task.getId()));
			return t;
		}
		return new HashMap<String,Object>();
	}
	/**
	 * 查询会签节点下的其它任务情况,
	 * @param taskId
	 * @return
	 */
	public ArrayList<HashMap<String,Object>> queryTaskListBytaskId(String taskId){
		// TODO Auto-generated method stub
		taskService.createTaskQuery().singleResult();
		return null;
	}
	public void addParam(String inst_id,String taskId,HashMap<String,Object> map) throws Exception{
		SQLInsertBean bean=new SQLInsertBean("S_WF_Parameter_Info");
		bean.putColumn("guid",SN_GUID.getUUID());
		bean.putColumn("status","1");
		bean.putColumn("createby","apiuser");
		bean.putColumn("createtime",new Date());
		bean.putColumn("updateby","apiuser");
		bean.putColumn("updatetime",new Date());
		bean.putColumn("wf_proc_inst_id",inst_id);
		bean.putColumn("taskId",taskId);
		bean.putColumn("json",new Gson().toJson(map));
		excuteSqlBean(bean);
	}
	@SuppressWarnings("unchecked")
	public HashMap<String,Object> getParam(String inst_id,String taskId) throws Exception{
		String sql="select json from S_WF_Parameter_Info where wf_proc_inst_id=? and taskId=? ";
		SQLResultBean resultBean=querySqlToSQLResultBean(sql,new Object[]{inst_id,taskId});
		ArrayList<HashMap<String,Object>> mapList=resultBean.getMapList();;
		if(mapList.size() > 0){
			String json="" + mapList.get(0).get("json");
			if(!"".equalsIgnoreCase(("" + json).replace("null",""))){
				return new HashMap<String,Object>(new Gson().fromJson(json,LinkedHashMap.class));
			}
		}else{
		}
		return new HashMap<String,Object>();
	}
}
